package com.atguigu.controller;

import com.atguigu.bean.Department;
import com.atguigu.bean.Employee;
import com.atguigu.dao.DepartmentDao;
import com.atguigu.dao.EmployeeDao;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Collection;

/**
 * @author wk
 * @create 2021-06-09 21:26
 * <p>
 * /employee     GET    查询全部用户信息
 * /employee/1   GET    根据id查询某个用户信息
 * /employee     post   添加用户
 * /employee     put    更新用户
 * /employee/1   delete 根据id删除用户
 */
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;


    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public String testGetEmployeeList(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("employees", employees);
        return "list";
    }

    @RequestMapping(value = "/toAdd", method = RequestMethod.GET)
    public String toAdd(Model model) {
        // 将所有的部门名称都查询出来
        // 在页面中以下拉框的方式展示，让用户选择
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments", departments);
        return "add";
    }

    @RequestMapping(value = "/employee", method = RequestMethod.POST)
    public String addEmployee(Employee employee) {
        System.out.println(employee);
        employeeDao.saveOrUpdate(employee);
        return "redirect:/employee";
    }
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
    public String toUpdate(@PathVariable("id") Integer id, Model model){
        // 根据id将用户信息查询出来
        Employee employee = employeeDao.get(id);
        // 将所有的部门信息查询出来在页面显示供用户选择修改
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("employee",employee);
        model.addAttribute("departments",departments);
        return "update";
    }
    @RequestMapping(value = "/employee",method = RequestMethod.PUT)
    public String updateEmployee(Employee employee){
        employeeDao.saveOrUpdate(employee);
        return "redirect:/employee";
    }
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable("id")Integer id){
        employeeDao.delete(id);
        return "redirect:/employee";
    }

}
